package com.tnovoselec.android.ui;

import java.util.List;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class MyScrollMenu extends HorizontalScrollView implements OnClickListener {

	public interface ChannelSelected {
		public void onChannelSelected(int position);
	}

	private RadioGroup radiogroup;
	private int tabLayoutId;
	private ChannelSelected channelListener;

	public MyScrollMenu(Context context) {
		this(context, null);
	}

	public MyScrollMenu(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public MyScrollMenu(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		try {
			TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyViewPagerTab2, defStyle, 0);
			tabLayoutId = a.getResourceId(R.styleable.MyViewPagerTab2_tabLayout, R.layout.my_view_pager_tab_2_indicator);
			a.recycle();
		} catch (Exception e) {
			// DO NIX
		}

		radiogroup = new RadioGroup(getContext());
		radiogroup.setOrientation(LinearLayout.HORIZONTAL);
		addView(radiogroup, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
	}

	@Override
	public void onClick(View v) {
		if (channelListener != null) {
			channelListener.onChannelSelected(radiogroup.indexOfChild(v));
		}

	}

	public void setChannels(List<String> channels) {
		radiogroup.removeAllViews();
		for (int i = 0; i < channels.size(); i++) {
			String channel = channels.get(i);
			View v = getTabIndicator(i, channel);
			radiogroup.addView(v);
		}
		if (radiogroup.getChildCount() > 0) {
			radiogroup.getChildAt(0).performClick();
		}
		requestLayout();
	}

	protected View getTabIndicator(final int position, CharSequence title) {
		final RadioButton radioButton = (RadioButton) LayoutInflater.from(getContext()).inflate(tabLayoutId, radiogroup, false);
		radioButton.setText(title);
		radioButton.setOnClickListener(this);
		return radioButton;
	}

	public ChannelSelected getChannelListener() {
		return channelListener;
	}

	public void setChannelListener(ChannelSelected channelListener) {
		this.channelListener = channelListener;
	}

}
